<!--
 * @Author: Dorange.Wang
 * @Date: 2021-03-31 16:04:51
 * @LastEditors: wangming
 * @LastEditTime: 2022-05-07 10:53:22
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="700px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建字段" : "编辑字段" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>
    <el-form class="pl30 pr30" :model="formData" ref="form" label-width="140px">
      <el-form-item
        v-if="formData.modelType !== 'VIEW'"
        label="字段编码"
        prop="code"
        :rules="[
          { required: true, message: '字段编码不能为空', trigger: 'change' },
          {
            pattern: COMMON_CODE_REG_64,
            message: '请输入有效的字段编码',
            trigger: 'change',
          },
          { validator: codeValidator, trigger: 'change' },
        ]"
      >
        <template slot="label"
          >字段编码
          <el-tooltip
            popper-class="custom-popper"
            :content="COMMON_CODE_REG_64_MSG"
            placement="top"
          >
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <el-input
          :disabled="!isNew && modelInfo.type !== 'VIRTUAL'"
          v-model="formData.code"
          style="width: 400px"
          placeholder="请输入字段编码"
          :maxlength="64"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item
        v-else
        label="字段编码"
        prop="code"
        :rules="[
          { required: true, message: '请选择字段编码', trigger: 'change' },
        ]"
      >
        <el-select
          :disabled="!isNew"
          v-model="formData.code"
          style="width: 400px"
          placeholder="请选择字段编码"
        >
          <el-option
            v-for="item in viewColumns"
            :key="item.name"
            :value="item.name"
            :label="item.name"
          >
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 14px">{{
              item.type
            }}</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="字段名称"
        prop="name"
        :rules="[
          { required: true, message: '字段名称不能为空', trigger: 'change' },
        ]"
      >
        <el-input
          :disabled="isProcessTitle"
          v-model="formData.name"
          style="width: 400px"
          placeholder="请输入字段名称"
          :maxlength="64"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item
        label="数据类型"
        prop="type"
        :rules="[
          { required: true, message: '请选择数据类型', trigger: 'change' },
        ]"
      >
        <el-select
          :disabled="
            (!isNew && modelInfo.type !== 'VIRTUAL') ||
            (modelInfo.type === 'VIRTUAL' &&
              disabledVirtualType.includes(formData.type))
          "
          v-model="formData.type"
          style="width: 400px"
          @change="changeType"
        >
          <el-option
            v-for="(value, key) in fieldDataType"
            :key="key"
            :value="key"
            :label="value"
          />
        </el-select>
      </el-form-item>
      <!--      关联选择-->
      <template v-if="needRelateType.includes(formData.type)">
        <el-form-item
          label="关联类型"
          prop="relationType"
          :rules="[
            { required: true, message: '请选择关联类型', trigger: 'change' },
          ]"
        >
          <el-radio-group
            v-model="formData.relationType"
            :disabled="!isNew && modelInfo.type !== 'VIRTUAL'"
            @change="changeRelateTypeRadio"
          >
            <el-radio
              v-for="(value, key) in FIELD_RELATE_TYPE_ENUM"
              :key="key"
              :label="key"
              >{{ value }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formData.relationType === 'BUSINESS'">
          <el-form-item
            label="业务模型"
            prop="config.modelCode"
            :rules="[
              {
                required: formData.relationType === 'BUSINESS',
                message: '请选择业务模型',
                trigger: 'change',
              },
            ]"
          >
            <tree-select
              style="width: 400px"
              :disabled="!isNew && modelInfo.type !== 'VIRTUAL'"
              :loading="modelLoading"
              v-model="formData.config.modelCode"
              filterable
              :fieldMap="{
                value: 'id',
                label: 'name',
                disabled: 'disabled',
              }"
              :filterNodeMethod="filterNodeMethod"
              :treeData="modelList"
              @change="loadAllFields('showValue')"
            />
          </el-form-item>

          <el-form-item
            v-if="formData.relationType === 'BUSINESS'"
            label="显示值"
            prop="config.value"
            :rules="[
              {
                required: formData.relationType === 'BUSINESS',
                message: '请选择业务模型的显示值',
                trigger: 'change',
              },
            ]"
          >
            <LabelExpression
              style="width: 400px"
              v-model="formData.config.value"
              :fields="fieldList"
            />
          </el-form-item>
        </template>

        <el-form-item
          v-if="formData.relationType === 'DICTIONARY'"
          label="字典类型"
          prop="config.value"
          :rules="[
            {
              required: formData.relationType === 'DICTIONARY',
              message: '请选择字典类型',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            :disabled="!isNew && modelInfo.type !== 'VIRTUAL'"
            v-model="formData.config.value"
            :loading="dictLoading"
            style="width: 400px"
            filterable
          >
            <el-option
              v-for="(item, index) in dictList"
              :key="index"
              :value="item"
              :label="item"
            />
          </el-select>
        </el-form-item>
      </template>
      <!--      子表-->
      <template v-if="formData.type === 'SUB_TABLE'">
        <el-form-item
          label="子业务模型"
          prop="config.modelCode"
          :rules="[
            {
              required: formData.type === 'SUB_TABLE',
              message: '请选择子业务模型',
              trigger: 'change',
            },
          ]"
        >
          <tree-select
            style="width: 400px"
            :disabled="!isNew && modelInfo.type !== 'VIRTUAL'"
            :loading="modelLoading"
            v-model="formData.config.modelCode"
            filterable
            :fieldMap="{
              value: 'id',
              label: 'name',
              disabled: 'disabled',
            }"
            :filterNodeMethod="filterNodeMethod"
            :treeData="modelList"
            @change="loadAllFields('showValue')"
          />
        </el-form-item>

        <el-form-item
          label="关联字段"
          prop="config.value"
          :rules="[
            {
              required: formData.type === 'SUB_TABLE',
              message: '请选择关联字段',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            :disabled="!isNew && modelInfo.type !== 'VIRTUAL'"
            v-model="formData.config.value"
            :loading="subLoading"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in fieldList"
              :key="index"
              :value="item.code"
              :label="`${item.name}(${item.code})`"
            />
          </el-select>
        </el-form-item>
      </template>
      <!--      序列号-->
      <template v-if="formData.type === 'SEQ'">
        <el-form-item
          label="序列号规则"
          prop="config.ruleCode"
          :rules="[
            {
              required: true,
              message: '序列号规则不能为空',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            v-model="formData.config.ruleCode"
            style="width: 400px"
            placeholder="请选择"
            @change="handleChangeSeq"
          >
            <el-option-group
              v-for="group in serialOptions"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="(item, index) in group.options"
                :key="group.label + index"
                :label="item.label"
                :value="item.ruleCode"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <div :class="{ 'warning-border': !seqValidFlag }">
          <div v-if="!seqValidFlag">
            <span style="color: #e6a23c">
              序列号规则的区段配置已变更，请重新配置序列号规则！
            </span>
            <el-button size="mini" plain type="primary" @click="resetSeqParam"
              >重置序列号规则
            </el-button>
          </div>

          <el-form-item
            label="Param参数"
            v-if="formData.paramVarValues && formData.paramVarValues.length"
            required
          ></el-form-item>
          <!--        param参数设置-->
          <div
            v-for="(item, index) in formData.paramVarValues"
            :key="'parameter' + index"
          >
            <el-form-item
              style="margin-bottom: 0px"
              :label="item.parameterName + '参数值'"
            >
              <template slot="label">
                <el-tooltip
                  popper-class="custom-popper"
                  :content="item.parameterName + '参数值'"
                  placement="top"
                >
                  <span class="label-eclispse"
                    >{{ item.parameterName + "参数值" }}
                  </span>
                </el-tooltip>
              </template>
              <!--            序列号类型-->
              <el-form-item
                style="display: inline-block; width: 30%"
                label-width="0px"
                :rules="[
                  {
                    required: true,
                    message: '类型不能为空',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="item.type"
                  @change="(val) => handleChangeSeqModelType(val, item)"
                >
                  <el-option value="MODEL" label="业务模型"></el-option>
                  <el-option value="FIX" label="固定值"></el-option>
                </el-select>
              </el-form-item>

              <!--            序列号字段-->
              <el-form-item
                style="
                  display: inline-block;
                  width: calc(70% - 10px);
                  margin-left: 10px;
                "
                v-if="item.type === 'MODEL'"
                label=""
                label-width="0px"
                :prop="'paramVarValues.' + index + '.value'"
                :rules="[
                  {
                    required: true,
                    message: '请选择字段',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="item.value"
                  :loading="subLoading"
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in fieldList"
                    :disabled="item.type === 'SEQ'"
                    :key="index"
                    :value="item.value"
                    :label="`${item.label}(${item.value})`"
                  />
                </el-select>
              </el-form-item>
              <!--            序列号固定值-->
              <el-form-item
                style="
                  display: inline-block;
                  width: calc(70% - 10px);
                  margin-left: 10px;
                "
                v-if="item.type === 'FIX'"
                label-width="0px"
                :prop="'paramVarValues.' + index + '.value'"
                :rules="[
                  {
                    required: true,
                    message: '参数值不能为空',
                    trigger: 'change',
                  },
                ]"
              >
                <el-input
                  :maxlength="item.startLength"
                  show-word-limit
                  placeholder="请输入"
                  v-model="item.value"
                >
                </el-input>
              </el-form-item>
            </el-form-item>
          </div>
          <!--        placeholder参数设置-->
          <el-form-item
            label="Placeholder参数"
            v-if="formData.phVarValues && formData.phVarValues.length"
            required
          ></el-form-item>
          <div
            v-for="(item, index) in formData.phVarValues"
            :key="'ph' + index"
          >
            <el-form-item
              style="margin-bottom: 0px"
              :label="item.parameterName + '参数值'"
            >
              <template slot="label">
                <el-tooltip
                  popper-class="custom-popper"
                  :content="item.parameterName + '参数值'"
                  placement="top"
                >
                  <span class="label-eclispse"
                    >{{ item.parameterName + "参数值" }}
                  </span>
                </el-tooltip>
              </template>
              <!--            序列号类型-->
              <el-form-item
                style="display: inline-block; width: 30%"
                label-width="0px"
                :prop="'phVarValues.' + index + '.type'"
                :rules="[
                  {
                    required: true,
                    message: '类型不能为空',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="item.type"
                  @change="(val) => handleChangeSeqModelType(val, item)"
                >
                  <el-option value="MODEL" label="业务模型"></el-option>
                  <el-option value="FIX" label="固定值"></el-option>
                </el-select>
              </el-form-item>

              <!--           placeholder 序列号字段 -->
              <el-form-item
                style="
                  display: inline-block;
                  width: calc(70% - 10px);
                  margin-left: 10px;
                "
                v-if="item.type === 'MODEL'"
                label=""
                label-width="0px"
                :prop="'phVarValues.' + index + '.value'"
                :rules="[
                  {
                    required: true,
                    message: '请选择字段',
                    trigger: 'change',
                  },
                ]"
              >
                <el-select
                  v-model="item.value"
                  filterable
                  :loading="subLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in fieldList"
                    :key="index"
                    :disabled="item.type === 'SEQ'"
                    :value="item.value"
                    :label="`${item.label}(${item.value})`"
                  />
                </el-select>
              </el-form-item>
              <!--           placeholder 序列号固定值-->
              <el-form-item
                style="
                  display: inline-block;
                  width: calc(70% - 10px);
                  margin-left: 10px;
                "
                v-if="item.type === 'FIX'"
                label-width="0px"
                :prop="'phVarValues.' + index + '.value'"
                :rules="[
                  {
                    required: true,
                    message: '参数值不能为空',
                    trigger: 'change',
                  },
                ]"
              >
                <el-input
                  :maxlength="item.startLength"
                  show-word-limit
                  placeholder="请输入"
                  v-model="item.value"
                >
                </el-input>
              </el-form-item>
            </el-form-item>
          </div>
        </div>
      </template>

      <el-form-item
        v-if="lenConfig.length > 0"
        label="长度"
        prop="length"
        :rules="[
          { required: true, message: '长度不能为空', trigger: 'change' },
        ]"
      >
        <el-input-number
          v-model="formData.length"
          :min="lenConfig[0]"
          :max="lenConfig[1]"
          style="width: 200px"
          controls-position="right"
        ></el-input-number>
      </el-form-item>

      <el-form-item
        v-if="
          formData.type === 'PARENT_ID' ||
          formData.type === 'STAFF' ||
          isProcessTitle
        "
        label="显示值"
        prop="config.value"
        :rules="[
          {
            required: formData.type === 'PARENT_ID',
            message: '请选择父节点的显示值',
            trigger: 'change',
          },
        ]"
      >
        <LabelExpression
          style="width: 400px"
          v-model="formData.config.value"
          :fields="
            formData.type === 'STAFF' ? staffDisplayRuleField : fieldList
          "
        />
      </el-form-item>
      <el-form-item
        prop="uniqueKey"
        v-if="needUniqueFields.includes(formData.type) && !isProcessTitle"
        label="唯一约束"
      >
        <el-checkbox
          v-model="formData.uniqueKey"
          :disabled="formData.type === 'SEQ'"
        >
        </el-checkbox>
      </el-form-item>
      <el-form-item prop="nullable" label="允许为空">
        <el-checkbox
          :disabled="
            formData.type === 'SEQ' ||
            formData.type === 'RELATION_PRIMARY_KEY' ||
            formData.uniqueKey
          "
          :true-label="1"
          :false-value="0"
          v-model="formData.nullable"
        >
        </el-checkbox>
      </el-form-item>
      <!-- 默认值 -->
      <el-form-item
        label="默认值"
        prop="defaultValue"
        v-if="showDefaultValue && !isProcessTitle"
      >
        <!-- 短文本 -->
        <el-input
          v-if="formData.type === 'SHORT_TEXT'"
          :maxlength="formData.length"
          show-word-limit
          v-model="formData.defaultValue"
          style="width: 400px"
          placeholder="请输入默认值"
        ></el-input>
        <!-- 长文本 -->
        <el-input
          v-if="formData.type === 'LONG_TEXT'"
          v-model="formData.defaultValue"
          style="width: 400px"
          placeholder="请输入默认值"
        ></el-input>
        <!-- 数值整型 -->
        <xInput
          v-if="['INTEGER', 'NUMBER'].includes(formData.type)"
          :limitNumber="formData.type === 'INTEGER' ? 0 : 8"
          placeholder="请输入默认值"
          size="small"
          style="width: 400px"
          :value="formData.defaultValue"
          @input="outInput"
        ></xInput>
        <!-- 布尔值 -->
        <el-radio-group
          v-model="formData.defaultValue"
          v-if="formData.type === 'BOOL'"
        >
          <el-radio :label="null">无</el-radio>
          <el-radio :label="true">TRUE</el-radio>
          <el-radio :label="false">FALSE</el-radio>
        </el-radio-group>
        <!-- 日期 -->
        <el-radio-group
          v-model="formData.defaultValueType"
          v-if="formData.type === 'DATE'"
        >
          <el-radio label="NONE">无</el-radio>
          <el-radio label="SYSTEM_VALUE">系统日期</el-radio>
          <el-radio label="FIX_VALUE">固定值</el-radio>
        </el-radio-group>
        <!-- 时间 -->
        <el-radio-group
          v-model="formData.defaultValueType"
          v-if="formData.type === 'TIME'"
        >
          <el-radio label="NONE">无</el-radio>
          <el-radio label="SYSTEM_VALUE">系统时间</el-radio>
          <el-radio label="FIX_VALUE">固定值</el-radio>
        </el-radio-group>
        <!-- 字典 -->
        <el-select
          v-model="formData.defaultValue"
          :multiple="formData.type === 'RELATION_SELECT' ? true : false"
          style="width: 100%"
          v-if="showDicDefaultValue"
        >
          <el-option
            v-for="item in dicOptiionValue"
            :key="item.optionValue"
            :value="item.optionValue"
            :label="item.optionName"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="
          ['DATE', 'TIME'].includes(formData.type) &&
          formData.defaultValueType === 'FIX_VALUE'
        "
      >
        <el-date-picker
          v-model="formData.defaultValue"
          v-if="formData.type === 'DATE'"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>

        <el-time-picker
          v-model="formData.defaultValue"
          v-if="formData.type === 'TIME'"
          value-format="HH:mm:ss"
          placeholder="选择时间"
        >
        </el-time-picker>
      </el-form-item>
      <el-form-item prop="localism" label="国际化" v-if="!isProcessTitle">
        <GlobalizationConfigWord
          :localism="formData.localism"
          @setLangCode="setLangCode"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="tr">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button :loading="confirmLoading" type="primary" @click="submit"
        >确 定
      </el-button>
      <el-button
        v-if="isNew"
        :loading="continueLoading"
        type="primary"
        @click="submit('continue')"
        >确定并继续添加
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import GlobalizationConfigWord from "@/components/globalizationConfigWord.vue";
import LabelExpression from "@/components/LabelExpression";
import {
  FIELD_DATA_TYPE_ENUM,
  FIELD_RELATE_TYPE_ENUM,
  VIRTUAL_TREE_FIELD_DATA_TYPE_ENUM,
} from "@/utils/enum";
import { COMMON_CODE_REG_64, COMMON_CODE_REG_64_MSG } from "@/utils/reg";
import {
  SYSTEM_FIELD,
  SYSTEM_FIELD_TREE,
  SYSTEM_FIELD_PROCESS,
} from "@/utils/const";

import { filterNodeMethod } from "@/utils/treeSelectFormat";
import { getHmdictionaryOptions } from "@/apis/paas/HmDictionaryController.js";

import lodash from "lodash";

import {
  postHmentitymodel,
  putHmentitymodel,
  getHmentitymodelList,
} from "@/apis/paas/HmEntityModelController.js";
import { getHmmodelViewcolumn } from "@/apis/paas/HmModelController.js";
import { getHmmodelfolderListTree } from "@/apis/paas/HmModelFolderController.js";
import { getHmdictionaryTypelist } from "@/apis/paas/HmDictionaryController.js";
import { getTechdefinesectionList } from "@/apis/paas/TechDefineSectionController.js";
import { getTechserialnumList } from "@/apis/paas/TechSerialNumController.js";
import xInput from "@/components/xInput/index.js";
var moment = require("moment");

const defaultaFormData = {
  relationType: Object.keys(FIELD_RELATE_TYPE_ENUM)[0],
};
const staffDisplayRuleField = [
  { label: "ID", value: "id" },
  { label: "账号", value: "username" },
  { label: "用户名", value: "name" },
  { label: "工号", value: "jobNumber" },
  { label: "邮箱", value: "email" },
  { label: "电话", value: "mobile" },
  { label: "英文名", value: "englishName" },
];
export default {
  name: "FieldForm",
  components: {
    LabelExpression,
    GlobalizationConfigWord,
    xInput,
  },
  data() {
    return {
      filterNodeMethod,
      serialOptions: [],
      showVisible: false,
      formData: {
        config: {},
      },
      disabledVirtualType: ["PARENT_ID", "PARENT_IDS", "CHILDREN"],
      needUniqueFields: [
        "SHORT_TEXT",
        "LONG_TEXT",
        "NUMBER",
        "DATE",
        "TIME",
        "STAFF",
        "DEPARTMENT",
        "INTEGER",
        "SEQ",
      ],
      fieldList: [],
      staffDisplayRuleField,
      lenConfig: [],
      disabledFields: [],
      fieldDataType: [],
      FIELD_DATA_TYPE_ENUM,
      VIRTUAL_TREE_FIELD_DATA_TYPE_ENUM,
      COMMON_CODE_REG_64,
      COMMON_CODE_REG_64_MSG,
      FIELD_RELATE_TYPE_ENUM,
      // 数据类型是关联选择时展示关联类型
      needRelateType: ["RELATION_SELECT", "RELATION_REFERENCE"],
      modelInfo: {},
      dictList: [],
      modelList: [],
      seqValidFlag: true,
      paramList: [], // 序列号参数list
      placeholdList: [], // 序列号的占位符list
      dictLoading: false,
      modelLoading: false,
      subLoading: false,
      confirmLoading: false,
      continueLoading: false,
      viewColumns: ["todo1", "todo2"],
      callback: () => {},
      codeValidator: (rule, value, callback) => {
        if (this.disabledFields.includes(value)) {
          callback(new Error("系统字段不可用"));
        } else {
          callback();
        }
      },
      dicOptiionValue: [],
    };
  },
  computed: {
    isNew() {
      return !this.formData.id;
    },
    showDefaultValue() {
      return (
        [
          "SHORT_TEXT",
          "LONG_TEXT",
          "NUMBER",
          "INTEGER",
          "DATE",
          "TIME",
          "BOOL",
        ].includes(this.formData.type) || this.showDicDefaultValue
      );
    },
    showDicDefaultValue() {
      return (
        ["RELATION_SELECT", "RELATION_REFERENCE"].includes(
          this.formData.type
        ) && this.formData.relationType === "DICTIONARY"
      );
    },
    isProcessTitle() {
      return (
        this.modelInfo.supportProcess &&
        this.formData.createType === "SYSTEM" &&
        this.formData.code === "process_title"
      );
    },
  },
  watch: {
    modelInfo: {
      handler: function (value) {
        this.fieldDataType = { ...FIELD_DATA_TYPE_ENUM };
        if (!value) return;
        if (value.type === "ENTITY") {
          this.disabledFields = SYSTEM_FIELD;
          if (value.supportTree) {
            if (this.formData.id) {
              // const treeField = [...SYSTEM_FIELD_TREE]
              // 移除parentId --- 可以编辑parentId
              // treeField.splice(0, 1)
              // this.disabledFields = [...this.disabledFields, treeField]
              // 为了回显父节点
              this.fieldDataType = { ...VIRTUAL_TREE_FIELD_DATA_TYPE_ENUM };
            } else {
              // this.disabledFields = [...this.disabledFields, ...SYSTEM_FIELD_TREE]
            }
          }
        }
        if (
          value.type === "VIRTUAL" &&
          !!value.supportTree &&
          this.formData.id &&
          this.disabledVirtualType.includes(this.formData.type)
        ) {
          this.fieldDataType = { ...VIRTUAL_TREE_FIELD_DATA_TYPE_ENUM };
        }
      },
      immediate: true,
      deep: true,
    },
    "formData.type": {
      handler: function (value) {
        if (value === "SUB_TABLE") {
          this.loadModelList();
        }
        if (value === "SEQ") {
          this.formData.uniqueKey = true;
          this.loadAllFields("self");
          this.getTechserialnumList();
        } else {
          if (!this.formData.id) {
            this.formData.uniqueKey = false;
          }
        }
        if (value === "RELATION_PRIMARY_KEY" || value === "SEQ") {
          this.formData.nullable = 0;
        }
        let length;
        let lenConfig = [];
        switch (value) {
          case "SHORT_TEXT":
            length = this.formData.length || 50;
            lenConfig = [1, 15000];
            break;
        }
        this.$set(this.formData, "length", length);
        this.lenConfig = lenConfig;
        if (
          this.formData.defaultValueType === "" &&
          ["DATE", "TIME"].includes(value)
        ) {
          this.$set(this.formData, "defaultValueType", "NONE");
        }
        if (
          ["true", "false", ""].includes(this.formData.defaultValue) &&
          value === "BOOL"
        ) {
          const flag =
            this.formData.defaultValue === "true"
              ? true
              : this.formData.defaultValue === "false"
              ? false
              : null;
          this.$set(this.formData, "defaultValue", flag);
        }

        if (value === "RELATION_SELECT" && this.formData.defaultValue) {
          const data = this.formData.defaultValue
            .match(/\[(\w+)\]/g)
            ?.map((item) => item.replace(/[[\]]/g, ""));
          this.$set(this.formData, "defaultValue", data);
        }
      },
      immediate: true,
    },
    "formData.defaultValueType": {
      handler(val) {
        if (["DATE", "TIME"].includes(this.formData.type)) {
          if (["NONE", "SYSTEM_VALUE"].includes(val)) {
            this.formData.defaultValue = "";
          }
        }
      },
    },
    "formData.uniqueKey": {
      handler: function (value) {
        if (value) {
          this.formData.nullable = 0;
        }
      },
      immediate: true,
    },
    "formData.relationType": {
      handler: function (value) {
        if (value === "BUSINESS" && this.modelList.length === 0) {
          this.loadModelList();
          return;
        }
        if (value === "DICTIONARY") {
          this.loadDictTypeList();
          return false;
        }
      },
      immediate: true,
    },

    showVisible(value) {
      if (value) {
        this.formData.modelType === "VIEW" && this.loadViewColumns();
      } else {
        this.viewColumns = [];
      }
    },

    "formData.config.value": {
      handler(val, oldVal) {
        if (val === "" && this.formData.relationType === "DICTIONARY") {
          this.formData.defaultValue = "";
        }
        if (this.formData.relationType === "DICTIONARY" && val) {
          if (this.formData.defaultValue && oldVal !== undefined) {
            this.formData.defaultValue = "";
          }
          this.getDicValueByType(val);
        }
      },
    },
  },

  methods: {
    async getDicValueByType(type) {
      const data = await getHmdictionaryOptions({ type: type });
      this.dicOptiionValue = data;
    },
    setLangCode(props) {
      this.formData.localism = props;
    },
    addForm(record = {}, modelInfo = {}) {
      this.formData = {
        ...record,
        nullable: 1,
        uniqueKey: false,
        config: {},
        paramVarValues: [],
        phVarValues: [],
        defaultValue: "",
        defaultValueType: "",
        localism: "",
      };
      this.modelInfo = modelInfo;
      return this.showModel();
    },
    editForm(record, modelInfo = {}) {
      this.formData = {
        localism: "",
        defaultValue: "",
        defaultValueType: "",
        ...record,
      };
      if (
        this.formData.type === "DATE" &&
        this.formData.defaultValueType === "FIX_VALUE" &&
        this.formData.defaultValue
      ) {
        this.formData.defaultValue = new Date(
          Number(this.formData.defaultValue)
        );
      }
      if (!this.formData.config) {
        this.formData.config = {};
      } else {
        this.formData.config = JSON.parse(record.config);
      }
      this.modelInfo = modelInfo;
      if (this.formData.type === "SUB_TABLE") {
        this.loadModelList("tableInit");
      }

      if (this.formData.type === "SEQ") {
        this.$set(
          this.formData,
          "paramVarValues",
          this.formData.config.paramVarValues
        );
        this.$set(
          this.formData,
          "phVarValues",
          this.formData.config.phVarValues
        );
        // 校验序列号是否发生变化
        this.checkSeqRule();
      }
      if (this.formData.relationType === "BUSINESS") {
        this.loadModelList("businessInit");
      }
      // 获取父节点的显示值字段
      if (this.formData.type === "PARENT_ID") {
        this.loadAllFields("self");
      }
      //流程标题获取当前模型下的业务字段
      if (this.isProcessTitle) {
        this.loadAllFields("self");
      }
      return this.showModel();
    },
    showModel() {
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      return {
        then: (callback) => {
          if (typeof callback === "function") {
            this.callback = callback;
          }
        },
      };
    },

    loadViewColumns() {
      getHmmodelViewcolumn({
        modelId: this.formData.modelId,
      }).then((res) => {
        this.viewColumns = res;
      });
    },
    // 获取所有业务模型
    loadModelList(flag = "") {
      this.modelLoading = true;
      getHmmodelfolderListTree({
        modelTypes:
          this.modelInfo.type === "VIRTUAL" ? "ENTITY,VIRTUAL" : "ENTITY",
      })
        .then((res) => {
          res.forEach((node) => {
            node.type = "folder";
          });
          this.modelList = this.createModelTreeNode(
            res || [],
            this.formData.modelId
          );
          if (flag === "tableInit") {
            this.loadAllFields("tableInit");
          }
          if (flag === "businessInit") {
            this.loadAllFields("businessInit");
          }
        })
        .finally(() => {
          this.modelLoading = false;
        });
    },
    loadDictTypeList() {
      this.dictLoading = false;
      getHmdictionaryTypelist()
        .then((res) => {
          this.dictList = res || [];
        })
        .finally(() => {
          this.dictLoading = false;
        });
    },
    // 加载模型的的字段--- 过滤草稿状态
    loadAllFields(flag) {
      // self 加载模型自身字段
      let modelId = "";
      if (flag === "self") {
        modelId = this.modelInfo.id;
      } else {
        if (!this.formData.config.modelCode) return;
        const item = this.getModelIdByCode(this.formData.config.modelCode);
        modelId = item.modelId;
      }
      this.subLoading = true;
      getHmentitymodelList({
        modelId: modelId,
        activated: true,
        skipRelationSelect: this.formData.type !== "PARENT_ID", // 过滤不支持递归翻译的字段  父节点ID放开过滤
      })
        .then((res) => {
          this.fieldList = res.filter((item) => item.status !== "SCRIPT");
          //如果是流程标题字段配置 需要过滤SYSTEM字段
          if (this.isProcessTitle) {
            this.fieldList = this.fieldList.filter(
              (i) =>
                i.createType !== "SYSTEM" &&
                ["LONG_TEXT", "SHORT_TEXT"].includes(i.type)
            );
          }
          // 子表只展示关联主键的字段
          if (this.formData.type === "SUB_TABLE") {
            this.fieldList = this.fieldList.filter(
              (item) => item.type === "RELATION_PRIMARY_KEY"
            );
          } else {
            this.fieldList = this.fieldList.filter(
              (item) => item.type !== "RELATION_PRIMARY_KEY"
            );
          }
          if (
            flag === "showValue" ||
            flag === "self" ||
            flag === "businessInit"
          ) {
            this.fieldList = this.fieldList.map((item) => {
              return {
                type: item.type,
                name: item.name,
                code: item.code,
                value: item.code,
                label: item.name,
              };
            });
          }
          if (
            flag === "tableInit" ||
            flag === "businessInit" ||
            flag === "self"
          ) {
            return;
          }
          this.$set(this.formData.config, "value", "");
        })
        .finally(() => {
          this.subLoading = false;
        });
    },

    getModelIdByCode(code) {
      let modelId = "";
      let supportTree = false;
      this.modelList.forEach((folder) => {
        const children = folder.modelResults || [];
        children.forEach((item) => {
          if (item.code === code) {
            modelId = item._id;
            supportTree = item.supportTree;
          }
        });
      });
      return { modelId, supportTree };
    },
    async submit(flag) {
      try {
        await this.$refs.form.validate();
        if (this.formData.nullable !== 1) {
          this.formData.nullable = 0;
        }
        const {
          id,
          modelId,
          code,
          name,
          type,
          length,
          nullable,
          uniqueKey,
          relationType,
          config,
          paramVarValues,
          phVarValues,
          defaultValue,
          defaultValueType,
          localism,
        } = this.formData;
        let params = {};
        let request = null;
        if (this.isNew) {
          params = {
            modelId,
            code,
            name,
            type,
            length,
            nullable,
            localism,
            defaultValue,
          };
          request = postHmentitymodel;
        } else {
          params = {
            id,
            code,
            name,
            type,
            length,
            nullable,
            localism,
            defaultValue,
          };
          request = putHmentitymodel;
        }
        if (["DATE", "TIME"].includes(this.formData.type)) {
          params.defaultValueType = defaultValueType;
        }
        if (
          this.formData.type === "DATE" &&
          this.formData.defaultValueType === "FIX_VALUE" &&
          this.formData.defaultValue
        ) {
          params.defaultValue = moment(this.formData.defaultValue).valueOf();
        }
        // 数据字典传值格式
        if (
          this.formData.type === "RELATION_SELECT" &&
          this.formData.relationType === "DICTIONARY"
        ) {
          let data = "";
          if (this.formData.defaultValue !== "") {
            data = this.formData.defaultValue
              ?.map((item) => `[${item}]`)
              ?.join("");
          }
          params.defaultValue = data;
        }
        if (
          this.formData.type === "BOOL" &&
          this.formData.defaultValue === "null"
        ) {
          params.defaultValue = "";
        }
        if (this.needUniqueFields.includes(type) && !this.isProcessTitle) {
          params.uniqueKey = uniqueKey;
        }
        if (this.formData.type !== "SEQ") {
          if (config) {
            delete config.ruleCode;
            delete config.paramVarValues;
            delete config.phVarValues;
          }
        }
        if (
          this.formData.relationType ||
          this.formData.type === "SUB_TABLE" ||
          this.formData.type === "SEQ"
        ) {
          if (
            this.formData.relationType === "DICTIONARY" ||
            this.formData.type === "SEQ"
          ) {
            delete config.modelCode;
          }
          if (this.formData.type === "SEQ") {
            delete config.value;
            params.bindInfo = config.value;
            config.paramVarValues = paramVarValues;
            config.phVarValues = phVarValues;
            params = {
              ...params,
              config: JSON.stringify(config),
            };
          } else {
            params = {
              ...params,
              relationType,
              config: JSON.stringify(config),
            };
          }
        }
        if (this.formData.type === "PARENT_ID") {
          delete config.modelCode;
          params = {
            ...params,
            config: JSON.stringify(config),
          };
        }
        if (this.formData.type === "STAFF") {
          delete config.modelCode;
          params = {
            ...params,
            config: !!config?.value ? JSON.stringify(config) : null,
          };
        }
        //流程标题 添加config
        if (this.isProcessTitle) {
          delete config.modelCode;
          params = {
            ...params,
            config: !!config?.value ? JSON.stringify(config) : null,
          };
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        if (flag === "continue") {
          this.continueLoading = true;
        } else {
          this.confirmLoading = true;
        }

        request(params)
          .then((res) => {
            if (flag === "continue") {
              this.formData = {
                ...this.formData,
                code: "",
                name: "",
                type: "",
                length: "",
                relationType: "",
                nullable: 1,
                uniqueKey: false,
                paramVarValues: [],
                phVarValues: [],
                config: {},
                defaultValue: "",
                defaultValueType: "",
                localism: "",
              };
              this.$nextTick(() => {
                this.$refs.form.clearValidate();
              });
              this.callback();
              return;
            }
            this.handleCancel();
            this.callback();
          })
          .finally(() => {
            this.confirmLoading = false;
            this.continueLoading = false;
          });
      } catch (error) {
        console.log(error);
      }
    },
    handleCancel() {
      this.showVisible = false;
      this.modelInfo = {};
      this.fieldList = [];
      this.dictList = [];
      this.modelList = [];
      this.seqValidFlag = true;
      this.paramList = [];
      this.formData = {
        config: {},
      };
      this.placeholdList = [];
    },
    changeType(value) {
      this.fieldList = [];
      if (this.needRelateType.includes(value)) {
        this.$set(this.formData, "relationType", defaultaFormData.relationType);
      }
      this.$set(this.formData.config, "value", "");
      this.$set(this.formData.config, "modelCode", "");
      this.$nextTick(() => {
        this.$refs.form.clearValidate([
          "nullable",
          "uniqueKey",
          "relationType",
          "config",
          "paramVarValues",
          "phVarValues",
          "defaultValue",
          "defaultValueType",
          "localism",
          "config.modelCode",
          "config.value",
        ]);
        // this.$refs.form.clearValidate("config.modelCode");
        // this.$refs.form.clearValidate("config.value");
      });
    },
    changeRelateTypeRadio(e) {
      this.formData.relationType = e;
      this.$set(this.formData.config, "value", "");
      this.$set(this.formData, "defaultValue", "");
      if (e === "DICTIONARY") {
        this.$set(this.formData.config, "modelCode", "");
        this.$set(this.formData, "defaultValue", []);
      } else {
        this.fieldList = [];
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate([
          "nullable",
          "uniqueKey",
          "relationType",
          "config",
          "paramVarValues",
          "phVarValues",
          "defaultValue",
          "defaultValueType",
          "localism",
        ]);
        // this.$refs.form.clearValidate("config.value");
        // this.$refs.form.clearValidate("config.modelCode");
      });
    },
    // 序列号
    getTechserialnumList() {
      getTechserialnumList().then((res) => {
        const data = res || {};
        this.serialOptions = [];
        this.serialOptions.push({
          label: "动态规则",
          options: data.DYNAMIC || [],
        });
        this.serialOptions.push({
          label: "静态规则",
          options: data.STATIC || [],
        });
      });
    },
    createModelTreeNode(tree, idDisabled = "") {
      return lodash.cloneDeep(tree).map((node) => {
        node.disabled = node.type === "folder";
        if (node.modelResults) {
          node.id = "folder" + node.id;
          node.children = node.modelResults || [];
          node.children.forEach((item) => {
            item.disabled = item.id == idDisabled;
            item._id = item.id;
            item.id = item.code;
            item.name = `${item.name}（${item.code}）`;
          });
        }
        return node;
      });
    },
    handleChangeSeq(val) {
      let id = "";
      this.serialOptions.forEach((item) => {
        item.options.forEach((data) => {
          if (data.ruleCode === val) {
            id = data.id;
          }
        });
      });
      if (!id) return;
      getTechdefinesectionList({ serialNumId: id }).then((res) => {
        const sectionList = res || [];
        let listParam = [];
        let listPh = [];
        this.paramList = sectionList.filter((d) => d.sectionType === "Param");
        listParam = this.paramList.map((item) => {
          return {
            id: item.id,
            startLength: item.startLength,
            parameterName: item.parameter,
            type: "MODEL",
            value: "",
          };
        });
        this.placeholderList = sectionList.filter(
          (d) => d.sectionType === "Placeholder"
        );
        listPh = this.placeholderList.map((item) => {
          return {
            id: item.id,
            startLength: item.startLength,
            parameterName: item.parameter,
            type: "MODEL",
            value: "",
          };
        });
        this.formData.paramVarValues = [];
        this.$set(this.formData, "paramVarValues", listParam);
        this.formData.phVarValues = [];
        this.$set(this.formData, "phVarValues", listPh);
        this.$forceUpdate();
      });
    },
    handleChangeSeqModelType(val, item) {
      item.value = "";
      if (val === "MODEL") {
        this.loadAllFields("self");
      }
    },
    // 校验序列号规则配置是否发生变化
    async checkSeqRule() {
      const ruleCode = this.formData.config.ruleCode;
      if (!this.serialOptions.length) {
        const res = await getTechserialnumList();
        const data = res || {};
        this.serialOptions = [];
        this.serialOptions.push({
          label: "动态规则",
          options: data.DYNAMIC || [],
        });
        this.serialOptions.push({
          label: "静态规则",
          options: data.STATIC || [],
        });
      }
      let id = "";
      this.serialOptions.forEach((item) => {
        item.options.forEach((data) => {
          if (data.ruleCode === ruleCode) {
            id = data.id;
          }
        });
      });
      if (id) {
        getTechdefinesectionList({ serialNumId: id }).then((res) => {
          const sectionList = res || [];

          this.paramList = sectionList.filter((d) => d.sectionType === "Param");
          this.placeholderList = sectionList.filter(
            (d) => d.sectionType === "Placeholder"
          );
          const formParamList = this.formData.config?.paramVarValues || [];
          const formPhList = this.formData.config?.phVarValues || [];
          let flag = true;
          if (formParamList.length !== this.paramList.length) {
            flag = false;
          }
          if (formPhList.length !== this.placeholderList.length) {
            flag = false;
          }
          this.paramList.forEach((serialItem, index) => {
            const formItem = formParamList[index];
            // const checkList = ['id']
            if (serialItem.id !== formItem?.id) {
              flag = false;
            }
          });

          this.placeholderList.forEach((serialItem, index) => {
            const formItem = formPhList[index];
            // const checkList = ['id']
            if (serialItem.id !== formItem?.id) {
              flag = false;
            }
          });
          this.seqValidFlag = flag;
        });
      }
      // 获取最新的区段定义
    },
    resetSeqParam() {
      let listParam = [];
      let listPh = [];
      listParam = this.paramList.map((item) => {
        return {
          id: item.id,
          startLength: item.startLength,
          parameterName: item.parameter,
          type: "MODEL",
          value: "",
        };
      });
      listPh = this.placeholderList.map((item) => {
        return {
          id: item.id,
          startLength: item.startLength,
          parameterName: item.parameter,
          type: "MODEL",
          value: "",
        };
      });
      this.formData.paramVarValues = [];
      this.$set(this.formData, "paramVarValues", listParam);
      this.formData.phVarValues = [];
      this.$set(this.formData, "phVarValues", listPh);
      this.$forceUpdate();
    },
    outInput(v) {
      if (v !== 0 && !v) {
        this.formData.defaultValue = null;
      } else {
        this.formData.defaultValue = Number(v);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.label-eclispse {
  width: 130px !important;
  float: left !important;
  white-space: nowrap;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

.warning-border {
  border: 2px solid #f56c6c;
  padding: 5px;
}
</style>
